<?php
/**
 * Created by PhpStorm.
 * User: clcw908
 * Date: 2016/10/27
 * Time: 14:03
 */
namespace AuctionCore\PurchaseOrder;

use AuctionBack\Logic\TransferLogic;
use AuctionCore\Agent\Agent;
use AuctionCore\Agent\Reward;
use AuctionCore\Agent\RewardLog;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\CarOwner\Owner;
use AuctionCore\CarResource\Car;
use AuctionCore\CarResource\CarCheck;
use AuctionCore\CarResource\CarSource;
use AuctionCore\Common\PhpRedis;
use AuctionCore\Dispute\Dispute;
use AuctionCore\Other\Inbox;
use AuctionCore\System\SystemConf;
use Think\Log;


class PurchaseOrder
{

    /**
     * 采购单Model
     *
     * @var Model|\Think\Model
     */
    private $purchaseOrderModel;

    /**
     * 采购单号
     *
     * @var string
     */
    private $id;

    private $redis;

    /**
     * 构造函数
     *
     * PurchaseOrder constructor.
     *
     * @param string $id 采购单号
     */
    function __construct($id = '')
    {
        $this->purchaseOrderModel = M('purchase_order');
        $this->id = $id;
        $this->redis = new PhpRedis(0);
    }

    /**
     * 添加采购单
     *
     * @param array $purchaseOrderArr 采购单数组
     *
     * @return mixed 返回采购单号
     */
    public function add($purchaseOrderArr)
    {
        $sid = $purchaseOrderArr['sid'];
        if ($sid == 0) {
            return false;
        }
        $purchaseOrderId = $this->purchaseOrderModel->add($purchaseOrderArr);
        return $purchaseOrderId;
    }

    /**
     * 生成采购单号
     *
     * @param int $purchaseOrderType 采购单类型，1 平台采购  2 公司自收
     *
     * @return string
     */
    public function generatePurchaseOrderNu($purchaseOrderType)
    {
        $orderNu = genBillsNo('CG', $purchaseOrderType);
        $purchaseOrderNu = $orderNu;//采购单号
        $data = $this->getPurchaseOrderByNu($purchaseOrderNu);
        if (empty($data)) {
            return $orderNu;
        } else {
            $this->generatePurchaseOrderNu($purchaseOrderType);
        }
    }

    /**
     * 生成随机组合字符串
     *
     * @param int $num               生成多少位的
     * @param int $purchaseOrderType 采购单类型 1 平台采购 2 公司自收
     *
     * @return string 返回生成的字符串
     */
    public function generateRandString($num, $purchaseOrderType)
    {
        $date = date('Ymd', time());
        $str = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        $randStr = '';
        for ($i = 0; $i < $num; $i++) {
            $randStr .= $str[rand(0, 61)];
        }
        if (preg_match('/^\d*$/', $randStr) || preg_match('/^[a-zA-Z]*$/', $randStr)) { //如果是纯数字或者纯字母，则继续循环
            $this->generateRandString();
        } else {
            $orderNu = 'CG' . $purchaseOrderType . $date . $randStr;
            return $orderNu;
        }
    }


    /**
     * 编辑采购单
     *
     * @param array $purchaseOrderArr 采购单数组
     *
     * @return bool 返回编辑的结果
     */
    public function edit($purchaseOrderArr)
    {
        $map = [
            'id' => $this->id,
        ];
        return $this->purchaseOrderModel->where($map)->save($purchaseOrderArr);
    }

    /**
     * 删除采购单
     *
     * @return mixed
     */
    private function delete()
    {
        $map = [
            'id' => $this->id,
        ];
        return $this->purchaseOrderModel->where($map)->delete();
    }

    /**
     * 根据采购单Id，获取采购单详情
     *
     * @return mixed
     */
    public function viewById()
    {
        $map = [
            'id' => $this->id,
        ];
        $arr = $this->purchaseOrderModel->where($map)->select();
        return $this->sortingData($arr)[0];
    }


    /**
     * 根据车辆Id，获取采购单详情
     *
     * @param int $carId 车辆编号
     *
     * @return mixed
     */
    public function viewByCarId($carId)
    {
        $map = [
            'car_id' => $carId,
        ];
        $arr = $this->purchaseOrderModel->where($map)->select();
        return $this->sortingData($arr)[0];
    }

    /**
     * 根据车辆sid，获取采购单详情
     *
     * @param int $sid 车辆sid
     *
     * @return mixed
     */
    public function viewBySid($sid)
    {
        $map = [
            'sid' => $sid,
        ];
        $arr = $this->purchaseOrderModel->where($map)->select();
        if (empty($arr)) {
            return [];
        }

        return $this->sortingData($arr)[0];
    }


    public static function viewByOrderId($order_id)
    {
        $map = [
            'order_id' => $order_id,
        ];
        $arr = M("purchase_order")->where($map)->find();
        return $arr;
    }

    /**
     * 根据采购单编号，获取采购单信息
     *
     * @param int $purchaseOrderNu 采购单编号
     *
     * @return mixed
     */
    public function getPurchaseOrderByNu($purchaseOrderNu)
    {
        $map = [
            'purchase_order_nu' => $purchaseOrderNu,
        ];
        return $this->purchaseOrderModel->where($map)->find();
    }

    /**
     * 获取采购单列表
     *
     * @param int $page     当前页数
     * @param int $pageSize 每页显示条数
     * @param int $params   参数
     *
     * @return array 返回结果数组
     */
    public function getList($page, $pageSize, $params)
    {
        $page = $page < 1 ? 1 : (int)$page;
        $pageSize = $pageSize < 1 ? 10 : (int)$pageSize;
        $map = [];
        if (!empty($params['purchase_order_nu'])) {
            $map['pu_order.purchase_order_nu'] = ['eq', $params['purchase_order_nu']];
        }

        if (!empty($params['order_no'])) {
            $map['pu_order.order_no'] = ['eq', $params['order_no']];
        }

        if ($params['starttime'] && !$params['endtime']) {
            $map['pu_order.createtime'] = ['egt', $params['starttime'] . " 00:00:00"];
        }
        if ($params['endtime'] && !$params['starttime']) {
            $map['pu_order.createtime'] = ['elt', $params['endtime'] . " 23:59:59"];
        }
        if ($params['starttime'] && $params['endtime']) {
            $map['pu_order.createtime'] = [['egt', $params['starttime'] . " 00:00:00"], ['elt', $params['endtime'] . " 23:59:59"]];
        }

        if (!empty($params['location_area'])) {
            $map['c.location_area'] = array('in', $params['location_area']);
        }

        $order = 'createtime desc';
        $field = 'pu_order.id,pu_order.purchase_order_nu,pu_order.order_no,pu_order.car_id,pu_order.sid,pu_order.amount,
                  pu_order.type,pu_order.status,pu_order.emp_id,pu_order.is_lock,pu_order.createtime,o.status as order_status';

        $total = $this->purchaseOrderModel->alias('pu_order')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'order as o ON o.order_id = pu_order.order_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'cars as c ON pu_order.car_id = c.car_id')
            ->where($map)
            ->count();
        //echo M()->getLastSql();

        $list = $this->purchaseOrderModel->alias('pu_order')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'order as o ON o.order_id = pu_order.order_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'cars as c ON pu_order.car_id = c.car_id')
            ->field($field)
            ->where($map)
            ->order($order)
            ->page($page)
            ->limit($pageSize)
            ->select();

        // echo M()->getLastSql();
        $list = $this->sortingData($list);

        foreach ($list as $key => $val) {
            $list[$key]['is_dispute'] = true;
            $sid = $val['sid'];//order_status
            $orderInfo = AuOrder::getNewestOrderBySid($sid);
            $list[$key]['order_status'] = $orderInfo['status'];
            $list[$key]['is_other_channel_deal'] = $orderInfo['is_other_channel_deal'];
            $transferLogic = new TransferLogic();
            $transferInfo = $transferLogic->getTransferLogInfoByOrderId($orderInfo['order_id']);
            $list[$key]['transfer_result'] = $transferInfo['result']; //过户结果:(0待过户;1开始过户2过户成功3过户失败4提档)

            $purchaseOrderId = $val['id'];
            $condition['order_id'] = $orderInfo['order_id']; //拍单id
            $condition['od_type'] = 2; //客户类型 2 车主
            $condition['order_status'] = $orderInfo['status'];//拍单状态
            $disputeCount = Dispute::getDisputeByPurchaseOrder($condition);
            if ($disputeCount > 0) {
                $list[$key]['is_dispute'] = false; //不能发起争议
            }
        }
        /* echo "<pre>";
         print_r($list);
         echo "</pre>";*/
        return [
            'list' => $list,
            'total' => $total,
        ];
    }

    /**
     * 处理数组
     *
     * @param array $arr 需要处理的数组
     *
     * @return mixed
     */
    public function sortingData($arr)
    {
        foreach ($arr as $key => $value) {
            $status = $value['status']; //采购单状态
            $type = $value['type']; //采购单类型
            $arr[$key]['type_name'] = C('PURCHASE_ORDER_TYPE.' . $type); //类型名称
            if ($value['is_lock'] == 1) { //如果是锁定状态
                $arr[$key]['status_name'] = '锁定';
            } else {
                $arr[$key]['status_name'] = C('PURCHASE_ORDER_STATUS.' . $status); //状态名称
            }

            $createBy = $value['emp_id'];//创建人
            $arr[$key]['create_by'] = $this->getUserById($createBy)['real_name'];
        }
        return $arr;
    }

    /**
     *  根据员工Id，获取员工信息
     *
     * @param $userId
     *
     * @return mixed
     */
    public function getUserById($userId)
    {
        $m = M("employee");
        $info = $m->find($userId);
        return $info;
    }

    /**
     * 根据采购单编号，锁定采购单
     *
     * @param $purchaseOrderNu
     *
     * @return bool
     */
    public function lockByPurchaseOrderNu($purchaseOrderNu)
    {
        $arr = $this->getPurchaseOrderByNu($purchaseOrderNu);

        if ($arr['status'] == 2 || $arr['status'] == 3) { //采购单完成和关闭时，不能在锁定
            return false;
        }

        if ($arr['is_lock'] == '1') {
            return true;
        }

        $map = [
            'purchase_order_nu' => $purchaseOrderNu,
        ];

        $data = [
            'is_lock' => '1',
            'modify_time' => date('Y-m-d H:i:s', time()),
        ];
        return $this->purchaseOrderModel->where($map)->save($data);
    }


    /**
     * 根据采购单Id，锁定采购单
     *
     * @return bool
     */
    public function lockById()
    {
        $arr = $this->viewById();

        if ($arr['is_lock'] == '1') {
            return true;
        }

        if ($arr['status'] == 2 || $arr['status'] == 3) { //采购单完成和关闭时，不能在锁定
            return false;
        }

        $map = [
            'id' => $this->id,
        ];

        $data = [
            'is_lock' => '1',
            'modify_time' => date('Y-m-d H:i:s', time()),
        ];
        return $this->purchaseOrderModel->where($map)->save($data);
    }


    /**
     * 根据采购单编号，解锁采购单
     *
     * @param $purchaseOrderNu
     *
     * @return bool
     */
    public function unLockByPurchaseOrderNu($purchaseOrderNu)
    {
        $arr = $this->getPurchaseOrderByNu($purchaseOrderNu);

        if ($arr['status'] == 2 || $arr['status'] == 3) { //采购单关闭和完成时，不能在锁定
            return false;
        }

        $map = [
            'purchase_order_nu' => $purchaseOrderNu,
        ];
        $data = [
            'is_lock' => '0',
            'modify_time' => date('Y-m-d H:i:s', time()),
        ];
        return $this->purchaseOrderModel->where($map)->save($data);
    }

    /**
     * 根据采购单Id，解锁采购单
     *
     * @return bool
     */
    public function unLockById()
    {
        $arr = $this->viewById();
        if ($arr['status'] == 2 || $arr['status'] == 3) { //如果采购单已关闭或者完成，就不能解锁
            return false;
        }

        if ($arr['is_lock'] == '0') {
            return true;
        }

        $map = [
            'id' => $this->id,
        ];
        $data = [
            'is_lock' => '0',
            'modify_time' => date('Y-m-d H:i:s', time()),
        ];
        return $this->purchaseOrderModel->where($map)->save($data);
    }


    /**
     * 根据采购单号，关闭采购单
     *
     * @param $purchaseOrderNu
     *
     * @return bool
     */
    public function closeByPurchaseOrderNu($purchaseOrderNu)
    {
        $map = [
            'purchase_order_nu' => $purchaseOrderNu,
        ];
        $data = [
            'status' => '2',
            'modify_time' => date('Y-m-d H:i:s', time()),
            'is_lock' => 0, //解锁
        ];
        return $this->purchaseOrderModel->where($map)->save($data);
    }

    /**
     * 根据采购单id，关闭并解锁采购单
     *
     * @return bool
     */
    public function closeById($id = '')
    {
        if (empty($id)) {
            $map = [
                'id' => $this->id,
            ];
        } else {
            $this->id = $id;
            $map = [
                'id' => $this->id,
            ];
        }
        $puchaseOrderData = $this->viewById();
        $status = $puchaseOrderData['status'];
        if ($status == 3) { //如果采购单状态是已完成，就不用关闭
            return true;
        }
        $data = [
            'status' => '2',
            'modify_time' => date('Y-m-d H:i:s', time()),
            'is_lock' => 0, //解锁
        ];
        return $this->purchaseOrderModel->where($map)->save($data);
    }

    /**
     * 根据采购单号，完成采购单
     *
     * @param $purchaseOrderNu
     *
     * @return bool
     */
    public function finishByPurchaseOrderNu($purchaseOrderNu)
    {
        $map = [
            'purchase_order_nu' => $purchaseOrderNu,
        ];
        $data = [
            'status' => '3',
            'modify_time' => date('Y-m-d H:i:s', time()),
        ];
        return $this->purchaseOrderModel->where($map)->save($data);
    }

    /**
     * 根据采购单Id，完成采购单
     *
     * @param $id
     *
     * @return bool
     */
    public function finishById($id)
    {
        $map = [
            'id' => $id,
        ];
        $data = [
            'status' => '3',
            'modify_time' => date('Y-m-d H:i:s', time()),
        ];
        return $this->purchaseOrderModel->where($map)->save($data);
    }

    /**
     * 根据SID完成采购单
     *
     * @param $sid
     *
     * @return bool
     */
    public static function finishBySid($sid)
    {
        if ($sid < 1) return false;
        $where = ['sid' => $sid];
        $data = [
            'status' => 3,
            'modify_time' => date('Y-m-d H:i:s', time())
        ];
        return M("purchase_order")->where($where)->save($data);
    }

    /**
     * 根据采购ID找对应状态付款信息
     *
     * @param int $type 车辆来源
     *
     * @return int $payment_id
     */
    public function getPaymentIdByPoid($type)
    {
        $data = [];
        if ($type == 2) {
            $data['p.pay_type'] = ['eq', 2];
        } else {
            $data['p.pay_type'] = ['eq', 1];
        }

        $data['pp.po_id'] = $this->id;
        $purchase_payment = M('purchase_payments')->alias('pp')
            ->join(C('DB_PREFIX') . "payment as p ON pp.`payment_id` = p.`id`")
            ->where($data)->find();
        return $purchase_payment['payment_id'];
    }

    /**
     * 添加付款单采购单的关系
     *
     * @param int $purchaseOrderId 采购单编号
     * @param int $paymentId       付款单编号
     * @param int $paymentType     付款单类型
     *
     * @return mixed
     */
    public function addPaymentAndPurchaseOrderRelation($purchaseOrderId, $paymentId, $paymentType)
    {
        $data = [
            'po_id' => $purchaseOrderId,
            'payment_id' => $paymentId,
            'pay_type' => $paymentType,
            'createtime' => date('Y-m-d H:i:s', time()),
        ];
        return M('purchase_payments')->add($data);
    }

    /**
     * 获取采购付款关系信息
     *
     * @param string $purchaseOrderId 采购单号
     * @param array  $paymentType     付款类型
     *
     * @return mixed
     */
    public function getPaymentAndPurchaseOrderRelation($purchaseOrderId, $paymentType)
    {
        $map['po_id'] = ['eq', $purchaseOrderId];
        if (!empty($paymentType)) {
            $map['pay_type'] = ['in', $paymentType];
        }
        $data = M('purchase_payments')->field('id,pay_type,payment_id')->where($map)->find();
        return $data;
    }

    /**
     * 付款回调
     *
     * @param int $payType
     * @param int $empId
     * @return bool
     */
    public function paymentCallback($payType, $empId)
    {
        $res = true;
        $now = date('Y-m-d H:i:s');
        $info = $this->viewById();
        if (empty($info)) {
            Log::record("确认付款,采购单信息为空");
            return false;
        }


        $orderInfo = AuOrder::getNewestOrderBySid($info['sid']);
        $o = new AuOrder($orderInfo['order_id']);
        $c = new Car($orderInfo['car_id']);
        $carInfo = $c->detail();
        if ($payType == 1 || $payType == 2) {
            //更新采购单付款状态
            $purchaseOrderPayStatus = $carInfo['car_source'] == 1 ? 3 : 2; //4S店车源直接已完成，个人的已付首款
            $res = $this->edit([
                'pay_status' => $purchaseOrderPayStatus,
                'modify_time' => $now,
            ]);
            if (!$res) {
                Log::record("确认付款,更新采购单付款状态失败");
                return false;
            }
            //更新车源状态已付款
            $cs = new CarSource($carInfo['sid']);
            $carSourceInfo = $cs->getInfo();
            if ($carSourceInfo['status'] < 401) {
                $resCarSource = $cs->update(['status' => 401]);
                if (!$resCarSource) {
                    Log::record("确认付款,更新车源状态失败");
                    return false;
                }
            }
            //更新车辆付款状态
            $pay_status = 2;
            $res = Car::updatePayStatusBySid($carInfo['sid'], $pay_status);
            if (!$res) {
                Log::record("确认付款,更新报告状态失败");
                return false;
            }

            if ($orderInfo['dealer_pay_status'] == 3) {
                //其他渠道成交直接到过户
                if ($orderInfo['is_other_channel_deal'] == 1) {
                    if ($orderInfo['status'] < 9) {
                        //无需验车到过户
                        $resOrder = $o->update(['status' => 9]);
                        $transferLog = [];
                        $transferLog['order_id'] = $orderInfo['order_id'];
                        $transferLog['sid'] = $carInfo['sid'];
                        \AuctionBack\Logic\TransferLogic::addTransferLog($transferLog);
                        if (!$resOrder) {
                            Log::record("确认付款,更新拍单到过户失败");
                            return false;
                        }
                    }
                } else {
                    //检查验车状态
                    $carCheckInfo = CarCheck::detail_by_order_id($orderInfo['order_id']);
                    if (!empty($carCheckInfo) && $carCheckInfo['status'] == 2) {
                        $resOrder = $o->update(['status' => 9]);
                        $transferLog = [];
                        $transferLog['order_id'] = $orderInfo['order_id'];
                        $transferLog['sid'] = $carInfo['sid'];
                        \AuctionBack\Logic\TransferLogic::addTransferLog($transferLog);
                        if (!$resOrder) {
                            Log::record("确认付款,更新拍单到过户失败");
                            return false;
                        }
                        //发送消息
                        $uid = $o->get_uid_by_order();
                        $car_name = $c->get_car_name();
                        $content = "【 " . $car_name . " 】拍单编号：" . $orderInfo['order_no'] . "，付款成功。交付顾问正在过户中，敬请关注。";
                        Inbox::sendMessage($uid, '车辆待过户', $content);
                    }
                }
            }
            $actionName = "确认付首款";
        } elseif ($payType == 3) {

            $carData = [
                'pay_status' => 4,
                'car_status' => 9,
            ];
            $res = $c->update($carData); //付尾款
            if (!$res) {
                Log::record("确认付款,更新车辆状态失败");
                return false;
            }
            $orderData = [];
            $orderData['status'] = 13;
            $orderData['trade_time'] = $now;
            $res = $o->update($orderData);
            if (!$res) {
                Log::record("确认付款,更新拍单完成失败");
                return false;
            }
            //更新采购单
            $purchaseOrderData = [
                'pay_status' => 3,
                'modify_time' => $now,
            ];
            $res = $this->edit($purchaseOrderData);
            if (!$res) {
                Log::record("确认付款,更新采购单失败");
                return false;
            }
            $res = $this->finishById($this->id);
            if (!$res) {
                Log::record("确认付款,完成采购单失败");
                return false;
            }
            $actionName = "确认付尾款";

            //卖车成功发奖励
            $carOwner = $o->get_car_owner_id();
            $owner = new Owner($carOwner['owner_id']);
            //车主信息
            $ownerInfo = $owner->detail();
            if (!empty($ownerInfo['uid'])) {
                $keyName = getRedisKeyByCode('REDIS_KEY', '100000');
                $this->redis->lpush($keyName, json_encode(
                        [
                            'bizContent' =>
                                [
                                    'scoreType' => 12,
                                    'score' => 2000,
                                    'remark' => '',
                                    'userId' => (int)$ownerInfo['uid']
                                ],
                            'bizType' => 5
                        ]
                    )
                );
                $this->redis->lpush($keyName, json_encode(
                        [
                            'bizContent' =>
                                [
                                    'expType' => 12,
                                    'exp' => 100,
                                    'remark' => '',
                                    'userId' => (int)$ownerInfo['uid']
                                ],
                            'bizType' => 6
                        ]
                    )
                );
                $agentInfo = D('Agent','Logic')->getDetailByUid($ownerInfo['uid']);
                if (!empty($agentInfo) && $agentInfo['superior_id'] > 0) {
                    //发奖励
                    $saleCarAward = SystemConf::getConfByName('SALE_CAR_AWARD');
                    $saleCarAwardConf = json_decode($saleCarAward['value'], true);
                    if (!empty($saleCarAwardConf['cash']['isAward']) || !empty($saleCarAwardConf['integral']['isAward'])
                        || !empty($saleCarAwardConf['growth']['isAward'])
                    ) {
                        $this->sendReward($agentInfo['superior_id'], $agentInfo['aid'], $carOwner['car_id']);
                    }
                }
            }
        }
        //记录车辆跟踪日志
        \AuctionCore\CarResource\Car::add_car_trace_log($orderInfo['car_id'], [
            'action_name' => $actionName,
            'emp_id' => $empId
        ]);

        //记录拍品跟踪日志
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($orderInfo['order_id'], [
            'action_name' => $actionName,
            'emp_id' => $empId
        ]);

        return $res;
    }

    /**
     * 卖车交易成功奖励
     *
     * @param int $aid
     * @param int $superior_id
     * @param int $car_id
     */
    private function sendReward($superior_id = 0, $aid = 0, $car_id = 0)
    {
//        $superior_id = 363;
//        $aid = 712;
//        $car_id = 578;
        //获取经纪人信息
        $agent = D('Agent','Logic')->getDetailByAid($superior_id);
        //直接交易配置
        $saleCarAward = SystemConf::getConfByName('SALE_CAR_AWARD');
        $awardConf = json_decode($saleCarAward['value'], true);
        $cashRate = $awardConf['cash']['rate'];
        $integralRate = $awardConf['integral']['rate'];
        $growthRate = $awardConf['growth']['rate'];
        $totalCash = $totalIntegral = $totalGrowth = 0;
        if ($awardConf['cash']['isAward']) {
            $totalCash = $agent['superior_id'] > 0 ? $awardConf['cash']['amount'] : $awardConf['cash']['amount'] * $cashRate;
        }
        if ($awardConf['integral']['isAward']) {
            $totalIntegral = $agent['superior_id'] > 0 ? $awardConf['integral']['amount'] : $awardConf['integral']['amount'] * $integralRate;
        }
        if ($awardConf['growth']['isAward']) {
            $totalGrowth = $agent['superior_id'] > 0 ? $awardConf['growth']['amount'] : $awardConf['growth']['amount'] * $growthRate;
        }
        //添加奖励总账记录
        $rId = D('Reward','Logic')->add($agent['aid'], $aid, 2, $totalCash, $totalIntegral, $totalGrowth);
        //发奖励 - 现金
        $ret = $ret1 = $ret2 = $ret3 = true;
        if ($awardConf['cash']['isAward']) {
            $ret1 = D('RewardLog','Logic')->addCashLog($rId, $agent['aid'], $aid, 2, $totalCash * $cashRate, $car_id);
        }
        //发奖励 - 积分
        if ($awardConf['integral']['isAward']) {
            $ret2 = D('RewardLog','Logic')->addIntegralLog($rId, $agent['aid'], $aid, 2, $totalIntegral * $integralRate, $car_id);
        }
        //发奖励 - 成长值
        if ($awardConf['growth']['isAward']) {
            $ret3 = D('RewardLog','Logic')->addGrowthLog($rId, $agent['aid'], $aid, 2, $totalGrowth * $growthRate, $car_id);
        }
        //发送失败记录信息
        if (!$ret1 || !$ret2 || !$ret3) {
            Log::record("发奖励失败,r_id: $rId", 'ERR', true);
            return false;
        }
        //记录redis
        if ($agent['superior_id'] > 0) {
            $data = [
                'r_id' => $rId,
                'aid' => $agent['aid'],
                'other_aid' => $aid,
                'type' => 2,
                'cash' => $totalCash,
                'integral' => $totalIntegral,
                'growth' => $totalGrowth,
                'cash_isAward' => $awardConf['cash']['isAward'],
                'integral_isAward' => $awardConf['integral']['isAward'],
                'growth_isAward' => $awardConf['growth']['isAward'],
                'car_id' => $car_id,
                'create_time' => time()
            ];
            $key = getRedisKeyByCode('REDIS_KEY','100018');
            $ret = $this->redis->rPush($key, json_encode($data, JSON_UNESCAPED_UNICODE));
            //$ret = $this->redis->rPush('sale_car_award_list', json_encode($data, JSON_UNESCAPED_UNICODE));
        }
        return $ret;
    }


    /**
     * 通过sid 更新采购单信息
     *
     * @param int   $sid  车源id
     * @param array $data 采购单信息
     *
     * @return bool
     */
    public function updateBySid($sid, $data)
    {
        $map['sid'] = ['eq', $sid];
        return $this->purchaseOrderModel->where($map)->save($data);
    }

    /**
     * 验车
     *
     * @param $order_id
     *
     * @return bool
     */
    private function addTransferInfo($order_id)
    {
        $carCheckInfo = CarCheck::detail_by_order_id($order_id);
        $res = true;
        $o = new AuOrder($order_id);
        $orderInfo = $o->detail();
        $c = new Car($orderInfo['car_id']);
        $carInfo = $c->detail();
        $res = $c->update(['pay_status' => 2]);
        if (!$res) {
            Log::record("确认付款,更新车辆状态过户失败");
            return false;
        }
        if (!empty($carCheckInfo) && $carCheckInfo['status'] == 2) {
            $orderData = ['status' => 9];
            $transferLog = [];
            $transferLog['order_id'] = $orderInfo['order_id'];
            $transferLog['sid'] = $carInfo['sid'];
            \AuctionBack\Logic\TransferLogic::addTransferLog($transferLog);
            //发送消息
            $uid = $o->get_uid_by_order();
            $car_name = $c->get_car_name();
            $content = "【 " . $car_name . " 】拍单编号：" . $orderInfo['order_no'] . "，付款成功。交付顾问正在过户中，敬请关注。";
            Inbox::sendMessage($uid, '车辆待过户', $content);
            $res = $o->update($orderData);
            if (!$res) {
                Log::record("确认付款,更新拍单状态到过户失败");
                return false;
            }
        }
        return $res;
    }

    /**
     * 根据SID更新采购单order_id
     *
     * @param $sid
     * @param $orderId
     * @param $orderNumber
     *
     * @return bool
     */
    public static function updateOrderIdBySid($sid, $orderId, $orderNumber)
    {
        if ($sid < 1 || $orderId < 1) return false;
        return M("purchase_order")->where(['sid' => $sid])->save(['order_id' => $orderId, 'order_no' => $orderNumber]);
    }

    /**
     * 根据sid获取采购单付款状态
     *
     * @param $sid
     *
     * @return bool|mixed
     */
    public static function getPayStatusBySid($sid)
    {
        if ($sid < 1) return false;
        return M("purchase_order")->where(['sid' => $sid])->getField("pay_status");
    }
}